import { createActions, handleMutations } from '@axios'
import * as actionTypes from '../actions/work-weixin'
import api from '../api/work-weixin'
import { isDevelopment, getLocalStorage, setLocalStorage, readEmployee } from '@/utils'
import { reduce, includes } from 'lodash-es'
import { EMPLOYEE_INFO, STORAGE_FIELD_LIST, DISPLAY_DOMAIN_MODULE, STORAGE_PERMISSION_LIST } from '@/utils/enums'
import { genMaterialStream } from '@/utils/streaming'

const defaultHeadline = require('@/assets/img/empty-icon.png')

const defaultHeadlineInfo = {
  headline: defaultHeadline,
  tagline: '您的暖心管家上线啦！',
}


const employeeInfo = JSON.parse(getLocalStorage(EMPLOYEE_INFO)) || {}
const permissionList =
  JSON.parse(getLocalStorage(STORAGE_PERMISSION_LIST)) || []
const displayDomainModule =
  JSON.parse(getLocalStorage(DISPLAY_DOMAIN_MODULE)) || []
const workWeixin = {
  namespaced: true,
  state: {
    /**
     * 当前员工的信息
     */
    wxUserInfo: {},
    employeeInfo: isDevelopment() ? { userId: readEmployee().employeeId } : employeeInfo,
    currentUserId: '',
    isTokenReady: isDevelopment() ? true : Boolean(employeeInfo),
    mgrFlag: 0,
    entryEnv: '',
    groupId: isDevelopment() ? process.env.VUE_APP_GROUP_ID : '',
    permissionList: permissionList,
    displayDomainModule: isDevelopment() ? ['BUSINESS', 'PERSONNEL'] : displayDomainModule, // 对公or对私的权限
    unionId: isDevelopment() ? 'osS4D6ZhLSL_ZX3UECCRGcKIeqLE' : null, // 微信客户的唯一标识,对公对私认证要用到
    fieldList: isDevelopment()
      ? [
        {
          fieldId: 'PERSONNEL',
          name: '客户经营管理',
          fieldType: 'QWGJ',
          group: '对私',
          isAdmin: 0
        },
        {
          fieldId: 'BUSINESS',
          name: '普惠客户经营',
          fieldType: 'HQJLY',
          group: '对公',
          isAdmin: 1
        }
      ] : [],
    // 领域列表
    fieldEnums: isDevelopment() ? { QWGJ: 'PERSONNEL', HQJLY: 'BUSINESS' } : {},

    headlineInfo: {
      ...defaultHeadlineInfo
    }
  },
  getters: {
    /**
     * 是否是管理员
     * @return {boolean}
     */
    isAdmin(state) {
      return Number(state.mgrFlag) === 1
    },

    permissionMap(state) {
      return reduce(
        [],
        (prev, key) => ({
          ...prev,
          [key]: includes(state.permissionList, key)
        }),
        {}
      )
    },
  },
  mutations: {
    ...handleMutations({
      /**
       * @description 获取员工信息
       */
      [actionTypes.GET_EMPLOYEE_INFO]: {
        success(state, payload) {
          state.employeeInfo.userId = payload.userId
          state.currentUserId = payload.userId
          state.employeeInfo.userName = payload.userName
          state.employeeInfo.headUrl = payload.headUrl
          state.isTokenReady = true
          state.displayDomainModule = payload.displayDomainModule
          state.fieldList = payload.fieldList
          setLocalStorage(
            DISPLAY_DOMAIN_MODULE,
            JSON.stringify(payload.displayDomainModule)
          )
          setLocalStorage(
            STORAGE_FIELD_LIST,
            JSON.stringify(payload.fieldList)
          )
          const fieldEnums = {}
          for (const field of payload.fieldList) {
            fieldEnums[field.fieldType] = field.fieldId
          }
          state.fieldEnums = fieldEnums
        }
      },
      // 设置微信用户信息
      [actionTypes.SET_WXUSER_INFO]: {
        success(state, payload) {
          state.wxUserInfo.openId = payload.openId
          state.wxUserInfo.unionId = payload.unionId
          state.wxUserInfo.nickName = payload.nickName
          state.wxUserInfo.headimgurl = payload.headimgurl
          state.wxUserInfo.sex = payload.sex
          state.wxUserInfo.city = payload.city
          state.wxUserInfo.country = payload.country
        }
      },
      // 设置用户权限列表
      [actionTypes.GET_USER_PERMISSION]: {
        success(state, payload) {
          state.employeeInfo.deptId = payload.deptId
          state.employeeInfo.deptName = payload.deptName
          state.permissionList = payload.permissionList
          state.mgrFlag = payload.mgrFlag
          setLocalStorage(EMPLOYEE_INFO, JSON.stringify(state.employeeInfo))
          setLocalStorage(
            STORAGE_PERMISSION_LIST,
            JSON.stringify(payload.permissionList)
          )
        }
      },
      // 设置领域列表
      [actionTypes.SET_USER_FIELD_LIST] (state, data) {
        state.fieldList = data
      },
      // 设置权限列表
      [actionTypes.SET_USER_PERMISSION_LIST] (state, data) {
        state.permissionList = data
      },
      // 设置用户是否是管理员
      [actionTypes.SET_ADMIN_ROLE] (state, data) {
        state.mgrFlag = data
      },
      [actionTypes.SET_HEADLINE_INFO]: {
        success(state, payload) {
          state.headlineInfo = {
            headline: payload.titleImgKey ? genMaterialStream('getTmpImage', payload.titleImgKey) : defaultHeadlineInfo.headline,
            tagline: payload.tagline ? payload.tagline.replace(/\n/g, '<br/>') : defaultHeadlineInfo.tagline.replace(/\n/g, '<br/>'),
          }
        }
      },
    }),
    setEntryEnv(state, payload) {
      state.entryEnv = payload
    },
    setGroupId(state, payload) {
      state.groupId = payload
    },
    setUnionId(state, payload) {
      state.unionId = payload
    }
  },
  actions: {
    ...createActions({
      ...api
    }),
    setEntryEnv(context, payload) {
      context.commit('setEntryEnv', payload)
    },
    setGroupId(context, payload) {
      context.commit('setGroupId', payload)
    },
    setUnionId(context, payload) {
      context.commit('setUnionId', payload)
    }
  }
}

export default workWeixin
